import axios from 'axios';
import { Message } from 'element-ui';

const service = axios.create({
  baseURL: 'http://localhost:8083',
  timeout: 10000,
  withCredentials: true,
});

service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 如果定制码不是200，则判定为错误。
    if (res.code !== 10000) {
      Message({ type: 'error', message: res.msg });
      // 508: 非法令牌;512: 其他客户已登录;514: 令牌过期;
      if (res.code === 10022 || res.code === 10008 || res.code === 503) {
        // to re-login
      }
      return Promise.reject(new Error(res.msg || '出现错误，请稍后再试'));
    } else {
      return res;
    }
  },
  (error) => {
    Message({ type: 'error', message: error.message });
    return Promise.reject(error);
  }
);

export default service;
